package com.acmedcare.framework.exchange.center.executer;

import com.acmedcare.framework.exchange.center.entity.bean.Task;
import com.acmedcare.framework.exchange.center.core.storage.RunnerRepository;
import com.acmedcare.framework.exchange.center.core.storage.TaskRunner;
import java.util.List;

public class TaskRunnerManager {

  final RunnerRepository runnerRepository;

  public TaskRunnerManager() {

    runnerRepository = (RunnerRepository) ExecutorConfig.getInstance()
        .getApplicationContext().getBean("runnerRepository");
  }

  public void addTask(Task task) {

    TaskRunner runner = runnerRepository.getRunner(task.getTaskId());
    if (runner == null) {

      runner = new TaskRunner();
      runner.setTaskId(task.getTaskId());
      runner.setName(task.getName());
      runner.setRunner(
          ExecutorConfig.getInstance().getGroupName() + "-" + ExecutorConfig.getInstance()
              .getExecutorName());
      runner.setCount(0);
      runner.setRunning(false);

      runnerRepository.createRunner(runner);
    }
  }


  public void register(Task task) {

    addTask(task);
    runnerRepository.addCount(task.getTaskId(), ExecutorConfig.getInstance().getGroupName());
  }

  public boolean isRun(Task task) {

    TaskRunner runner = runnerRepository.getRunner(task.getTaskId());
    if (runner != null && runner.getCount() > 0) {

      return true;
    }

    return false;
  }

  public void unRegister(Task task) {

    runnerRepository.deleteCount(task.getTaskId());
  }

  public List<TaskRunner> getRunning() {

    return runnerRepository.getRunning();
  }
}
